from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.oxml.ns import qn
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL
from docx.enum.style import WD_STYLE_TYPE
from docx.oxml import OxmlElement
from docx.oxml.ns import nsdecls
import os


def create_word_document(output_path):
    """创建一个包含各种元素的Word文档"""

    # 创建一个新的Word文档
    doc = Document()

    # 添加文档标题
    title = doc.add_heading('Python生成的Word文档示例', level=0)
    title.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = title.runs[0]
    run.font.size = Pt(24)
    run.font.color.rgb = RGBColor(0, 0, 139)  # 深蓝色
    run.font.bold = True

    # 添加副标题
    subtitle = doc.add_heading('使用python-docx库', level=1)
    subtitle.alignment = WD_ALIGN_PARAGRAPH.CENTER
    run = subtitle.runs[0]
    run.font.size = Pt(18)
    run.font.color.rgb = RGBColor(70, 130, 180)  # 钢蓝色
    run.font.italic = True

    # 添加日期和作者信息
    doc.add_paragraph().add_run('创建日期: 2023年11月15日').italic = True
    doc.add_paragraph().add_run('作者: Python开发者').italic = True
    doc.add_paragraph()  # 空行

    # 添加章节1: 简介
    doc.add_heading('1. 简介', level=1)
    doc.add_paragraph(
        "本文档展示了如何使用Python创建和格式化Word文档。"
        "python-docx库提供了丰富的功能，可以生成专业级的文档。"
    )

    # 添加带格式的段落
    p = doc.add_paragraph()
    p.paragraph_format.space_after = Pt(12)  # 段落后间距
    p.paragraph_format.line_spacing_rule = WD_LINE_SPACING.ONE_POINT_FIVE  # 1.5倍行距

    run = p.add_run("主要功能包括:")
    run.bold = True
    run.font.size = Pt(14)

    # 添加项目符号列表
    doc.add_paragraph("添加标题和段落", style='List Bullet')
    doc.add_paragraph("创建表格和格式化单元格", style='List Bullet')
    doc.add_paragraph("插入图片和图表", style='List Bullet')
    doc.add_paragraph("应用样式和格式", style='List Bullet')
    doc.add_paragraph("添加页眉和页脚", style='List Bullet')
    doc.add_paragraph()  # 空行

    # 添加章节2: 表格示例
    doc.add_heading('2. 表格示例', level=1)

    # 创建表格
    table = doc.add_table(rows=4, cols=3)
    table.style = 'Medium Grid 1 Accent 1'  # 应用表格样式
    table.alignment = WD_TABLE_ALIGNMENT.CENTER

    # 设置表格标题行
    hdr_cells = table.rows[0].cells
    hdr_cells[0].text = '产品名称'
    hdr_cells[1].text = '描述'
    hdr_cells[2].text = '价格 (¥)'

    # 格式化标题行
    for cell in hdr_cells:
        cell.paragraphs[0].runs[0].bold = True
        cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER

    # 添加表格数据
    data = [
        ('Python基础教程', '入门级Python编程指南', '89.00'),
        ('数据分析实战', '使用Pandas和NumPy进行数据分析', '128.00'),
        ('机器学习实践', 'Scikit-learn和TensorFlow实战', '156.00')
    ]

    for i, (name, desc, price) in enumerate(data, start=1):
        row_cells = table.rows[i].cells
        row_cells[0].text = name
        row_cells[1].text = desc
        row_cells[2].text = price

        # 设置价格列右对齐
        row_cells[2].paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT

    doc.add_paragraph()  # 空行

    # 添加章节3: 格式化文本
    doc.add_heading('3. 文本格式化', level=1)

    # 添加不同格式的文本
    p = doc.add_paragraph()
    p.add_run("粗体文本 ").bold = True
    p.add_run("斜体文本 ").italic = True
    p.add_run("下划线文本 ").underline = True
    p.add_run("删除线文本 ").font.strike = True

    p = doc.add_paragraph()
    p.add_run("小号字体 ").font.size = Pt(10)
    p.add_run("正常字体 ")
    p.add_run("大号字体 ").font.size = Pt(14)

    p = doc.add_paragraph()
    p.add_run("红色文本 ").font.color.rgb = RGBColor(255, 0, 0)
    p.add_run("绿色文本 ").font.color.rgb = RGBColor(0, 128, 0)
    p.add_run("蓝色文本 ").font.color.rgb = RGBColor(0, 0, 255)

    doc.add_paragraph()  # 空行

    # 添加章节4: 图片示例
    doc.add_heading('4. 图片示例', level=1)

    # 添加图片描述
    doc.add_paragraph("以下是Python logo的示例图片:")

    try:
        # 尝试添加图片（需要Pillow库）
        doc.add_picture('D:\hbyt\AI智能投标\markdown_output\media\研发特有_研发交付物清单&checklist示例_v1.0_22019\image0.png', width=Inches(2.0))
        doc.add_paragraph("图1: Python Logo", style='Caption')
    except:
        # 如果图片不存在，添加替代文本
        doc.add_paragraph("[图片: Python Logo]")

    doc.add_paragraph()  # 空行

    # 添加章节5: 高级格式化
    doc.add_heading('5. 高级格式化', level=1)

    # 添加引用块
    p = doc.add_paragraph(style='Intense Quote')
    p.alignment = WD_ALIGN_PARAGRAPH.CENTER
    p.add_run("编程不是一门科学，而是一门手艺。")

    # 添加代码块
    doc.add_heading('代码示例:', level=2)
    code = '''def hello_world():
    print("Hello, World!")

if __name__ == "__main__":
    hello_world()'''

    p = doc.add_paragraph()
    run = p.add_run(code)
    run.font.name = 'Consolas'
    run.font.size = Pt(11)
    run._element.rPr.rFonts.set(qn('w:eastAsia'), 'Consolas')  # 中文字体兼容

    # 添加页眉
    section = doc.sections[0]
    header = section.header
    header_para = header.paragraphs[0]
    header_para.text = "Python生成的Word文档示例"
    header_para.alignment = WD_ALIGN_PARAGRAPH.CENTER

    # 修复页脚页码问题 - 使用正确的XML元素创建方法
    footer = section.footer
    footer_para = footer.paragraphs[0]
    footer_para.alignment = WD_ALIGN_PARAGRAPH.CENTER

    # 创建页码字段的正确方法
    run = footer_para.add_run("页码: ")

    # 添加当前页码字段
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'begin')
    run._r.append(fldChar)

    instrText = OxmlElement('w:instrText')
    instrText.set(qn('xml:space'), 'preserve')
    instrText.text = "PAGE"
    run._r.append(instrText)

    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'end')
    run._r.append(fldChar)

    run = footer_para.add_run(" / ")

    # 添加总页数字段
    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'begin')
    run = footer_para.add_run()
    run._r.append(fldChar)

    instrText = OxmlElement('w:instrText')
    instrText.set(qn('xml:space'), 'preserve')
    instrText.text = "NUMPAGES"
    run._r.append(instrText)

    fldChar = OxmlElement('w:fldChar')
    fldChar.set(qn('w:fldCharType'), 'end')
    run._r.append(fldChar)

    # 保存文档
    doc.save(output_path)
    print(f"文档已成功创建: {output_path}")


def main():
    # 设置输出路径
    output_dir = "output"
    os.makedirs(output_dir, exist_ok=True)
    output_path = os.path.join(output_dir, "python_generated_document.docx")

    # 创建文档
    create_word_document(output_path)

    print("\n文档创建完成!")


if __name__ == "__main__":
    main()